package org.onion.pattern.kit.common.jackson.serializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

public class LocalDateDeserializer extends JsonDeserializer<LocalDate> {


    public static final DateTimeFormatter fmt_yyyy_MM_dd = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public  static LocalDate parse(String s){
        if (StringUtils.isBlank(s)) {
            return null;
        }

        //如果是数字
        if (StringUtils.isNumericSpace(s)) {
            return LocalDate.ofInstant(Instant.ofEpochMilli(Long.parseLong(s)), ZoneId.systemDefault());
        }

        try {
            return LocalDate.parse(s, fmt_yyyy_MM_dd);
        } catch (Exception e) {
            //
        }

        try {
            return LocalDate.parse(s, DateTimeFormatter.ISO_LOCAL_DATE);
        } catch (Exception e) {
            //
        }

        try {
            return LocalDate.parse(s+"-01", fmt_yyyy_MM_dd);
        } catch (Exception e) {
            throw new IllegalArgumentException("日期解析失败 " + s);
        }
    }


    @Override
    public LocalDate deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        if (ObjectUtils.isEmpty(jsonParser)) {
            return null;
        }

        String json = jsonParser.getText();
        if (StringUtils.isBlank(json)) {
            return null;
        }
        return parse(json);
    }


}
